package com.witsight.hibernate.helper;

import java.lang.reflect.Constructor;

import javax.persistence.AttributeConverter;
import javax.persistence.Convert;

import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.EnumJavaTypeDescriptor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.util.ReflectionUtils;

import com.witsight.platform.util.lang.ClassUtil;

/**   
 * 说明：枚举类型转换描述
 * @Title: ConvertEnumJavaTypeDescriptor.java 
 * @Package com.witsight.hibernate.helper 
 * @See: {@link EnumJavaTypeDescriptor}<br/>
 * Copyright: Copyright (c) 2017<br/>
 * Company:sany huax witsight team by product
 * @author: fuyp  
 * @date: 2017年12月7日 下午3:15:00 
 * @version: V1.0
 *
 */
@SuppressWarnings("rawtypes")
public class ConvertEnumJavaTypeDescriptor<T extends Enum> extends EnumJavaTypeDescriptor<T> {
	private static final long serialVersionUID = 658982344312623288L;
	private final AttributeConverter attributeConverter;
	public ConvertEnumJavaTypeDescriptor(Class<T> type, Convert convert) {
		super(type);
		if (ClassUtil.isSuperInterface(convert.converter(), AttributeConverter.class)) {
			Constructor<?> constructor = ReflectionUtils.findConstructor(convert.converter());
			this.attributeConverter = (AttributeConverter) BeanUtils.instantiateClass(constructor);
		} else {
			this.attributeConverter = null;
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <X> T wrap(X value, WrapperOptions options) {
		if (this.attributeConverter != null) {
			return (T) this.attributeConverter.convertToEntityAttribute(value);
		}
		return super.wrap(value, options);
	}
}
